import React, { useEffect, useState, useRef, useCallback } from 'react';
import {
  Modal,
  View,
  Text,
  TextInput,
  TouchableWithoutFeedback,
  Image,
  FlatList,
  Keyboard,
  Animated,
  PanResponder,
} from 'react-native';
import i18n from '../i18n';
import stylesXS from '../styles/xs';
import stylesMD from '../styles/md';
import stylesLG from '../styles/lg';
import dimesA5 from '../styles/size/a5';
import dimesA5X2 from '../styles/size/a5x2';
import dimesA6 from '../styles/size/nom';

import { DashView } from 'react-native-sticker-lib/src/view/DashView';

const ModalCreateGroup = ({
  modalVisible,
  onClose,
  onConfirm,
  title,
  btnOk,
  placeholder,
  value = '',
  status,
  onClearValueNm,
  screenWidth,
  screenHeight,
  stickerGroups = [],
  stickerList = [],
  headerStatus,
  stickerGroupItem,
  progress,
}) => {
  const [groupName, setGroupName] = useState('');
  const textInputRef = useRef(null);
  const flatListRef = useRef(null);
  const scrollY = useRef(new Animated.Value(0)).current;
  const thumbYValue = useRef(0);
  const lastThumbY = useRef(0);
  useEffect(() => {
    setGroupName(value);
  }, [value]);
  useEffect(() => {
    thumbYValue.current = 0; // Reset thumb position when component is mounted
    scrollY.setValue(0); // Reset FlatList scroll position
    if (
      (status === 1 || status === 2) &&
      modalVisible &&
      textInputRef.current
    ) {
      focusTextInput();
    }
  }, [status, modalVisible, focusTextInput]);
  const focusTextInput = useCallback(() => {
    if (textInputRef.current) {
      // 尝试使用 requestAnimationFrame，尽管在 React Native 中可能不是必需的
      requestAnimationFrame(() => {
        // 仍然使用 setTimeout 来确保足够的延迟
        setTimeout(() => {
          textInputRef?.current?.focus();
          textInputRef.current.setNativeProps({
            selection: {
              start: value?.length,
              end: value?.length,
            },
          });
        }, 200); // 根据需要调整延迟时间
      });
    }
  }, []);
  let wd = Math.round(screenWidth);
  const styles =
    wd === 1024 || wd === 1365
      ? stylesLG
      : wd === 994 || wd === 1325
        ? stylesMD
        : stylesXS;
  const nom = wd === 1024 || wd === 1365
    ? dimesA5X2
    : wd === 994 || wd === 1325
      ? dimesA5
      : dimesA6;

  // 列表的Item高度
  const itemHeight = styles.modalItemSty.height + nom.dp_px_2;
  // 列表的内容高度
  const listContentHeight = itemHeight * stickerGroups.length - nom.dp_px_2;
  // 列表可见区域高度
  const visibleHeight = styles.creatListHt_672.height;
  // 固定的滑块高度
  const thumbHeight = nom.dp_px_80;
  // 滑块可以移动的最大距离
  const maxThumbY = visibleHeight - thumbHeight;

  console.log("ModalCreateGroup listContentHeight:" + listContentHeight + "==" + visibleHeight);

  useEffect(() => {
    const id = scrollY.addListener(({ value }) => {
      const newThumbY = (value / (listContentHeight - visibleHeight)) * maxThumbY;
      thumbYValue.current = newThumbY;

    });
    return () => {
      scrollY.removeListener(id);
    };
  }, [scrollY, listContentHeight, visibleHeight, maxThumbY]);

  // 拖拽手势，用于同步拖动滑块和列表滚动
  const panResponder =
    PanResponder.create({
      onStartShouldSetPanResponder: () => true,
      onMoveShouldSetPanResponder: () => true,
      onPanResponderGrant: () => {
        lastThumbY.current = thumbYValue.current;
      },
      onPanResponderMove: (evt, gestureState) => {
        let newThumbY = lastThumbY.current + gestureState.dy;
        // 限制滑块移动范围
        if (newThumbY < 0) newThumbY = 0;
        if (newThumbY > maxThumbY) newThumbY = maxThumbY;
        // 根据滑块位置计算 FlatList 应滚动的 offset
        const scrollOffset = (newThumbY / maxThumbY) * (listContentHeight - visibleHeight);
        console.log("SideBar panResponder move:" + scrollOffset + "==" + flatListRef.current);
        if (flatListRef.current) {
          flatListRef.current.scrollToOffset({ offset: scrollOffset, animated: false });
        }
      },
      onPanResponderRelease: () => { },
    });

  // 联动动画：FlatList 滚动时同步调整滑块位置
  const animatedThumbY = scrollY.interpolate({
    inputRange: [0, listContentHeight - visibleHeight],
    outputRange: [0, maxThumbY],
    extrapolate: 'clamp',
  });


  const renderItem = itemData => {
    const item = itemData.item;
    const index = itemData.index;
    return (
      <View>
        <TouchableWithoutFeedback
          underlayColor={'#f9f9f9'}
          activeOpacity={0.25}
          onLongPress={() => onConfirm(item)}
          onPress={() => onConfirm(item)}>
          <View style={[styles.flexCenter, styles.modalItemSty,
            {
              marginHorizontal: nom.dp_px_64,
              borderBottomWidth:0,
              // borderBottomWidth: index === stickerGroups?.length - 1 ? 0
              //   : styles.modalItemSty.borderBottomWidth
            }
          ]}>
            <Image
              style={[
                styles.checkBtnWH,
                {
                  resizeMode: 'contain',
                },
              ]}
              source={
                item.thumb_sticker
                  ? { uri: `file://${item.thumb_sticker}` }
                  : item.id === 'recent'
                    ? require('../../assets/ic_recent.png')
                    : require('../../assets/ic_sticker.png')
              }
            />
            <Text
              style={[styles.modalTextFont, {
                flex: 1,
                textAlign: 'left',
                writingDirection: 'ltr'
              }]}
              ellipsizeMode={'middle'}
              numberOfLines={1}>
              {item.name}
            </Text>       
          </View>
        </TouchableWithoutFeedback>

        {index === stickerGroups?.length - 1 ? null : (<DashView
          style={{
            height: nom.dp_px_2,
            width: styles.modalItemSty.width,
            marginHorizontal: nom.dp_px_64
          }}
          dashWidth={nom.dp_px_2}
          gapWidth={nom.dp_px_4}
        />)}
             
            
      </View>
    );
  };
  return (
    <Modal animationType="slide" transparent={true} visible={modalVisible}>
      <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
        <View
          style={[
            styles.modalBg,
            {
              opacity: status === 41 || status === 431 ? 1 : 0,
              width: screenWidth,
              height: screenHeight,
            },
          ]}
        />
        <View style={styles.modalContainer}>
          <View
            style={[
              styles.borderWidth,
              styles.borderRadius_6,
              status === 5 ? styles.modalCardLand : styles.modalCardVertical,
              {
                backgroundColor: '#fff',
                borderWidth: nom.dp_px_2 - nom.dp_px_1 / 2
              },
            ]}>
            <View
              style={[
                styles.modalCardTitle,
                styles.bottomBorder,
                styles.createNmHt,
                {              
                  borderBottomWidth: nom.dp_px_1
                }
              ]}>
              <Text style={[styles.modalCardTitleText, styles.fontSize_40]}>
                {title}
              </Text>
            </View>
            {status === 5 ? (
              <View style={styles.creatListHt_672}>
                <FlatList
                  ref={flatListRef}
                  renderItem={(itemData) => renderItem(itemData)}
                  data={stickerGroups}
                  keyExtractor={(item, index) => index}
                  showsVerticalScrollIndicator={false}
                  onScroll={Animated.event(
                    [{ nativeEvent: { contentOffset: { y: scrollY } } }],
                    { useNativeDriver: false }
                  )}
                  scrollEventThrottle={16}
                />
                {listContentHeight > visibleHeight ? (
                  <View
                    style={{
                      position: 'absolute',
                      right: 0,
                      top: 0,
                      bottom: 0,
                      width: nom.dp_px_30,
                      justifyContent: 'flex-start',
                      alignItems: 'center',
                    }}
                  >
        
                    <Animated.View
                      style={{
                        width: nom.dp_px_30,
                        overflow: 'hidden',
                        height: thumbHeight,
                        transform: [{ translateY: animatedThumbY }]
                      }}
                      {...panResponder.panHandlers}
                    >
                      <Image source={require('../../assets/ic_slider.png')}
                        style={{
                          width: nom.dp_px_30,
                          height: '100%',
                          resizeMode: 'contain',
                        }}
                      ></Image>
        
                    </Animated.View>
                  </View>
        
                )
                  : null}
              </View>
            ) : (
                <View style={[styles.modalCardBody,
                {
                  minHeight: nom.dp_px_210,
                }
                ]}>
                {status === 1 || status === 2 ? (
                  <View style={{ position: 'absolute' }}>
                    <View
                      style={[
                        styles.modalTextInputCard,
                        styles.borderWidth,
                        styles.inputCard,
                      ]}>
                      <TextInput
                        style={[
                          styles.modalTextInputCard,
                          styles.inputCard,
                          styles.fontSize_34,
                          styles.paddingRl_20_100,
                          {
                            fontWeight: '400',
                            color: '#000',
                          },
                        ]}
                        ref={textInputRef}
                        selectTextOnFocus={false}
                        // maxLength={150}
                        placeholder={placeholder}
                        onChangeText={e => {
                          if (/^\s*$/.test(e)) {
                            setGroupName('');
                            return;
                          }
                          setGroupName(e);
                        }}
                        onBlur={() => {
                          Keyboard.dismiss();
                        }}
                        value={groupName}
                      />
                      {groupName ? (
                        <TouchableWithoutFeedback
                          onPress={() => {
                            setGroupName('');
                            onClearValueNm && onClearValueNm();
                          }}>
                          <Image
                            style={[styles.checkBtnWH, styles.closeBtn_88]}
                            source={require('../../assets/ic_close.png')}
                          />
                        </TouchableWithoutFeedback>
                      ) : null}
                    </View>
                  </View>
                ) : status === 4 ||
                  status === 41 ||
                  status === 42 ||
                  status === 432 ||
                  status === 431 ||
                  status === 54 ? (
                  <View
                    style={[
                      styles.borderWidth,
                      styles.progressCard,
                      styles.progressCardWidth,
                      {
                        flexDirection: 'row',
                        alignItems: 'center',
                        justifyContent: 'flex-start',
                        backgroundColor: '#fff',
                        overflow: 'hidden',
                      },
                    ]}>
                    <View
                      style={[
                        styles.progressCard,
                        {
                          backgroundColor: '#000',
                          width: styles.progressCardWidth.width * progress,
                        },
                      ]}
                    />
                  </View>
                ) : (
                  <View style={{ 
                    alignSelf: 'flex-start',
                    marginHorizontal: nom.dp_px_64,
                    marginVertical: nom.dp_px_64,
                   }}>
                    <Text style={[styles.modalButtonText,
                       styles.fontSize_34,
                      ]}>
                      {placeholder}
                    </Text>
                  </View>
                )}
              </View>
            )}
            {status === 431 || status === 432 ? null : (
              <View style={[styles.modalButtonCardStyle, styles.modalBtmCard,
                {
                  borderTopWidth: nom.dp_px_1
                }
              ]}>
                {
                  status === 61 ? null :(
                    <TouchableWithoutFeedback onPress={onClose}>
                    <View
                      style={[
                        styles.modalButtonStyle,
                        styles.modalCardBody,
                        styles.modalBoCard,
                        styles.borderWidth,
                        {
                          minWidth:nom.dp_px_198,
                          width:null,
                          paddingHorizontal:nom.dp_px_32,
                          borderWidth: nom.dp_px_2 - nom.dp_px_1 / 2,
                          overflow:'visible'
                        }
                      ]}>
                      <Text
                        numberOfLines={1}
                        style={[styles.modalButtonText, styles.fontSize_34,
                        {
                          textAlign:'center',
                          flexShrink: 0
                        }
                        ]}>
                        {i18n.t('btn.cancel')}
                      </Text>
                    </View>
                  </TouchableWithoutFeedback>
                  )
                }
                {btnOk && (
                  <TouchableWithoutFeedback
                    onPress={async () => {
                      console.log("btn ok press:"+status);
                      if (!groupName && (status === 1 || status === 2)) {
                        return;
                      }
                      
                      onConfirm(groupName);
                      setGroupName('');
                    }}>
                    <View
                      style={[
                        styles.modalButtonStyle,
                        styles.modalCardBody,
                        styles.modalBoCard,
                        {
                          minWidth:nom.dp_px_198,
                          width:null,
                          paddingHorizontal:nom.dp_px_32,
                          backgroundColor:
                            groupName ||
                              status === 3 ||
                              status === 6 ||
                              status === 7 ||
                              status === 62 ||
                              status === 63 ||
                              status === 61
                              ? '#000'
                              : '#999',
                        },
                      ]}>
                      <Text
                        numberOfLines={1}
                        style={[
                          styles.fontSize_34,
                          {
                            fontWeight: '400',
                            color: '#fff',
                            textAlign: 'center',
                            flexShrink: 0
                          },
                        ]}>
                          {btnOk}
                        {/* {status === 1
                          ? i18n.t('btn.create')
                          : status === 6
                            ? i18n.t('btn.jump')
                            : i18n.t('btn.ok')} */}
                      </Text>
                    </View>
                  </TouchableWithoutFeedback>
                )}
              </View>
            )}
          </View>
        </View>
      </View>
    </Modal>
  );
};

export default ModalCreateGroup;
